# 文件IO
# open函数

# 读文件
f1 = open("data/students.txt", mode='r', encoding='utf8')
# read(n) 表示读n个字符
# readline 读一行
# readlines 读所有的行 并构成list返回

print(f1.read(10))
print(f1.readline())
print(f1.readline())
print(f1.readlines())

# 关闭文件
f1.close()

# 写文件
f2 = open("data/newStu.txt", mode='w', encoding='utf8')

# 换行需要手动加上 \n
f2.write("必须传入字符串1\n")
f2.write("必须传入字符串2\n")
f2.write("必须传入字符串3\n")

f2.writelines(['一行数据\n', '一行数据\n', '一行数据\n', '一行数据\n'])

# 关闭文件
f2.close()

# with open 不需要手动的关闭文件
# 读取 students.txt的数据并写入newStu2.txt

with open("data/students.txt", mode="r", encoding='utf8') as f3:
    with open("data/newStu2.txt", mode='a', encoding='utf8') as f4:
        f4.writelines(f3.readlines())

# 操作MySQL
# pip install pymysql
import pymysql

# 创建连接
conn = pymysql.connect(user='root', passwd='123456', host='master', port=3306, database='student')

# 创建游标 类似statement
cursor = conn.cursor()
# 返回最后查询出来的条数
t = cursor.execute("select id,name,age from student where clazz like %s and gender=%s", ('理科%', '男'))
print("总计记录数：", t)

# print(cursor.fetchone())  # 返回一条记录
# print(cursor.fetchmany(3))  # 返回n条记录
# print(cursor.fetchall())  # 返回所有记录 注意使用

for i in range(t):
    print(cursor.fetchone())

# 关闭连接
cursor.close()
conn.close()

with pymysql.connect(user='root', passwd='123456', host='master', port=3306, database='student') as conn:
    with conn.cursor() as cursor:
        nums = cursor.execute("select * from student where age>%s", 23)
        for i in range(nums):
            print(cursor.fetchone())
        # conn.rollback() # 发生错误进行回滚
        # conn.commit() # 没有异常直接提交

# 格式化日期字符串
from datetime import datetime

# 字符串转datetime
dt = datetime.strptime("2021-12-07 16:41:38", "%Y-%m-%d %H:%M:%S")
print(dt, type(dt))

print(dt.year)
print(dt.month)
print(dt.day)
print(dt.weekday())

# datetime转字符串
# 2021/12/07 16:41:38
date_str = datetime.strftime(dt, "%Y/%m/%d %H:%M:%S")
print(date_str, type(date_str))
